<?php

class Router extends Object 
{
	public $controller, $action, $args;
    private static $__routers = null;
    private static $__parsedRouters = array();
    
	function __construct($routers = null)
	{
		$this->setRouters($routers);
	}

	public static function getInstance($routers = array())
	{
		static $instance;
		if (!is_object($instance))
		{
			$instance = new Router($routers);
		}
		return $instance;
	}
	
	public static function setRouters($routers)
	{
		if(!empty(self::$__parsedRouters)) return ;
		self::$__routers = $routers;
		foreach ($routers as $key => $val)
		{
			list($controller, $action) = explode('/', $val['aca']);
			$replacement = "controller=$controller&action=$action";
			if (strpos($key, '$') !== false) {  
				preg_match_all("/[{][$]([a-z_][0-9a-z_]*)[}]/", $key, $metches, PREG_PATTERN_ORDER);
				foreach ($metches[1] as $k => $var)
				{
					$replacement .= '&'.$var.'=$'.($k+1);
				}
				$controller = $action = '[0-9a-z_]+';
				extract($val['pattern']);
				$key = str_replace(array('{', '}'), array('({', '})'), $key);
				eval("\$key = \"$key\";");
			}
			self::$__parsedRouters[$key] = $replacement;
		}
	}
	

	public function execute()
	{
		$this->__parse();
		if (!isset($_GET['controller']) || empty($_GET['controller'])) $_GET['controller'] = Config::get('config', 'defaultController');
		if (!isset($_GET['action']) || empty($_GET['action'])) $_GET['action'] =  Config::get('config', 'defaultAction');
		$this->controller = $_GET['controller'];
		$this->action = $_GET['action'];
		$this->args = $_GET;
	}


	private function __parse()
	{
		$path_info = Env_Request::get_pathinfo();
		$url_info_array  = parse_url(SITE_URL);
		if($url_info_array['path'] !== '/') //如果程序放在了目录下
		{
			$path_info = '/' . substr($path_info, strlen($url_info_array['path']));
		}
		
		$path_info = Env_Request::get_pathinfo();

		if (isset(self::$__parsedRouters[$path_info])) {
			$query_string_replacement = self::$__parsedRouters[$path_info];
		} else {
			$patterns = array();
			foreach (self::$__parsedRouters as $pattern=>$v) {
				$patterns[] = '#^'.$pattern.'$#';
			}

			$query_string = preg_replace($patterns, self::$__parsedRouters, $path_info, 1);
			if ($query_string == $path_info) {
				$query_string = '';
				$args = explode('/', substr($path_info, 1));
				if (!empty($args)) $query_string .= '&controller='.array_shift($args);
				if (!empty($args)) $query_string .= '&action='.array_shift($args);
				if (!empty($args)) {
					$query_string .= '&';
					foreach ($args as $k=>$v) {
						$query_string .= $v.($k%2 == 0 ? '=' : '&');
					}
				}
			}

		}
		parse_str($query_string, $_GET);
		$_REQUEST = array_merge($_REQUEST, $_GET);
	}
}